package com.tom;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nl.captcha.Captcha;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    /**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
    	
    	String answer = request.getParameter("answer");
        request.getSession().removeAttribute("CAP_WRONG");
        Captcha cap = (Captcha)request.getSession().getAttribute(Captcha.NAME);
        if (!cap.isCorrect(answer)){
                request.getSession().setAttribute("CAP_WRONG", "驗證碼錯誤");
                RequestDispatcher disp = request.getRequestDispatcher("login.jsp");
                disp.forward(request, response);
                return;
        }
    	
    	String action = request.getParameter("action");
    	if (action.equalsIgnoreCase("login")){
    		String id = request.getParameter("id");
    		String password1 = request.getParameter("password1");
    		Member m = new Member(id,password1);
    		
    		HttpSession session = request.getSession();
    		session.setAttribute("m", m);
    		
    		if (m.login()){
    			response.sendRedirect("login_success.jsp");
//        	request.getRequestDispatcher("login_success.jsp")
//        	.forward(request, response);
    		}else{
    			response.sendRedirect("login.jsp");
    		}
    	}
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	
}
	


